package com.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    // 创建用户名--密码hashmap，用于模拟用户在数据库中存储的数据
    private Map<String, String> namePasswordMap = new HashMap<String, String>();

    {
        // 初始化用户测试数据
        namePasswordMap.put("xiaoming", "b5f7a18fe1d3285e61018bf7cab12fee");
    }




    // 获取授权信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 1、从认证信息中获取用户名
        String userName = (String)principalCollection.getPrimaryPrincipal();

        // 2、从数据库或者缓存中获取用户角色数据
        Set<String> roles = getRolesByUserName(userName);
        // 3、从数据库获取缓存中获取用的权限数据
        Set<String> permissions = getPermissionsByUserName(userName);

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);

        return authorizationInfo;
    }

    private Set<String> getPermissionsByUserName(String userName) {
        System.out.println("从内存中获取权限数据");
        Set<String> permissions = new HashSet<String>();
        permissions.add("delete");
        permissions.add("update");
        permissions.add("select");
        return permissions;
    }

    private Set<String> getRolesByUserName(String userName) {
        Set<String> roles = new HashSet<String>();
        roles.add("admin");
        return roles;
    }


    // 获取认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 1、从主体传过来的认证信息中，获取用户名
        String userName = (String) authenticationToken.getPrincipal();

        // 2、通过用户名从数据库中获取密码
        String password = getPasswordByUserName(userName);
        if (password != null) {
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, password, "customRealm");
            // 为认证方法设置盐值
            authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("aaabbb"));
            return authenticationInfo;
        }

        return null;
    }

    private String getPasswordByUserName(String userName) {
        return namePasswordMap.get(userName);
    }

}
